//
//  LLT_RegistViewController_LXM.m
//  CoderLLT
//
//  Created by 刘晓萌 on 15/12/9.
//  Copyright © 2015年 刘晓萌. All rights reserved.
//

#import "LLT_RegistViewController_LXM.h"
#import <AVOSCloud/AVOSCloud.h>
#import "UIViewController+LLT_LoginAndRegist_LXM.h"


@interface LLT_RegistViewController_LXM ()<UITextFieldDelegate>
//背景的滑动scrollView
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//用户名/手机号
@property (weak, nonatomic) IBOutlet UITextField *userNameField;
//密码/密码
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
//主体view
@property (weak, nonatomic) IBOutlet UIView *bodyView;
//验证码
@property (weak, nonatomic) IBOutlet UITextField *repeatPassword;

//重复滚动标记
@property (assign, nonatomic) BOOL flag;

//点击获取验证码的button
@property (weak, nonatomic) IBOutlet UIButton *getTokenButton;
//注册/提交
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
//忘记密码/新用户
@property (weak, nonatomic) IBOutlet UIButton *forgetAndNewUserButton;
//倒数计时属性
@property (assign,nonatomic) NSInteger time;

@property (strong,nonatomic) AVUser *avuser;
@end

@implementation LLT_RegistViewController_LXM

-(void)viewDidAppear:(BOOL)animated
{
    [NSTimer scheduledTimerWithTimeInterval:0.022 target:self selector:@selector(changBackImageAction) userInfo:nil repeats:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.avuser = [AVUser user];
    [self makeView];
    [self makeDelegate];
}


/**
 * 设置页面
 */
-(void)makeView{
    
    self.userNameField.text = self.userNameField.placeholder;
    self.passwordField.text = self.passwordField.placeholder;
    self.repeatPassword.text = self.repeatPassword.placeholder;
    
    
    if (self.pageTypeFlag) {
        //忘记密码页面
        [self.submitButton setTitle:@"找 回 密 码" forState:UIControlStateNormal];
        [self.forgetAndNewUserButton setTitle:@"新用户" forState:UIControlStateNormal];
       
    }else{
        //注册页面
        [self.submitButton setTitle:@"注 册" forState:UIControlStateNormal];
        [self.forgetAndNewUserButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    }

}


/**
 * 统一接收代理
 */
-(void)makeDelegate{
    self.userNameField.delegate = self;
    self.passwordField.delegate = self;
    self.repeatPassword.delegate = self;
}


/**
 * 设置滚动背景图
 */
-(void)changBackImageAction{
    NSInteger x = self.scrollView.contentOffset.x;
    NSInteger y = self.scrollView.contentOffset.y;
    if (self. flag) {
        self.scrollView.contentOffset = CGPointMake(x - 1, y);
        if ( x<= 2 ){
            self. flag = NO;
        }
    }else{
        self.scrollView.contentOffset = CGPointMake(x + 1, y);
        if (x + 2 >= (self.scrollView.contentSize.width - self.view.frame.size.width)) {
            self. flag = YES;
        }
    }
}


#pragma mark --- textFielf代理方法

/**
 * 文本框开始改变
 */
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    textField.text = nil;
       //密码框
    if(textField.tag == 911){
        textField.secureTextEntry = YES;
    }
    self.bodyView.bounds = CGRectMake(0, 40, self.bodyView.frame.size.width, self.bodyView.frame.size.height);
}

/**
 * 文本框将要结束修改
 */
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
    if (textField.text.length == 0 || [textField.text isEqualToString:textField.placeholder]) {
        textField.text = textField.placeholder;
        if(textField.tag == 911){
            textField.secureTextEntry = NO;
        }
    }else{
        //手机号框
        if(textField.tag == 920){
            BOOL flag = [self authenticatePhoneNum:textField.text];
            if (!flag) {
                [self showAlert:@"注 意" andAlertString:@"请输入正确的手机号" andHandler:^(UIAlertAction *action) {
                    textField.text = nil;
                }];
            }
        }
    }
    return YES;
}

#pragma mark --- 处理点击事件

/**
 * 点击屏幕四周的touch事件
 */
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.userNameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    [self.repeatPassword resignFirstResponder];
    self.bodyView.bounds = CGRectMake(0, 0, self.bodyView.frame.size.width, self.bodyView.frame.size.height);
}


- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

/**
 * 点击返回登陆按钮
 */
- (IBAction)didClickLoginButton:(UIButton *)sender {
    DissMissBack;
}

/**
 * 点击注册按钮/提交按钮
 */
- (IBAction)didClickRegistButton:(UIButton *)sender {
    [self registAndResetPassworAction];
}

/**
 * 点击忘记密码或新用户按键
 */
- (IBAction)didClickForgetOrNewUserButton:(UIButton *)sender {
    self.pageTypeFlag = !self.pageTypeFlag;
    [self makeView];
}

/**
 * 点击开始密码保护或者不开启
 */
- (IBAction)didClickShowSecretOrClose:(UIButton *)sender {
    self.passwordField.secureTextEntry = !self.passwordField.secureTextEntry;
}

/**
 * 点击获取验证码方法
 */
- (IBAction)didClickGetTokenButton:(UIButton *)sender {
    [self checkPhoneNum];
    self.time = 60;
    self.getTokenButton.titleLabel.text = @"60 s";
    [self.getTokenButton setTitle:@"60 s" forState:UIControlStateNormal];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeGetToken:) userInfo:nil repeats:YES];
    sender.userInteractionEnabled = NO;
    sender.backgroundColor = [UIColor grayColor];
    if (self.pageTypeFlag) {
        //NSLog(@"获取更改密码的验证码");
        [self getTokenForResetPassword];
    }else{
        [self getTokenAndRegist];
    }
}
#pragma mark --- 功能方法实现
/**
 * 注册和找回密码方法
 */
-(void)registAndResetPassworAction{
    //确认所有内容都非空且不等于placeHoder
    BOOL getLengthBool = self.userNameField.text.length == 0 || self.repeatPassword.text.length == 0 || self.passwordField.text.length == 0 ;
    BOOL getEqualBool = [self.userNameField.text isEqualToString:self.userNameField.placeholder] || [self.repeatPassword.text isEqualToString:self.repeatPassword.placeholder] || [self.passwordField.text isEqualToString:self.passwordField.placeholder];
    if (getLengthBool || getEqualBool) {
        [self showAlert:@"注 意" andAlertString:@"请输入正确的信息"];
    }else{
        if (self.pageTypeFlag) {
            [self resetPassword];
        }else{
            [self regist];
        }
    }
}

/**
 * 注册方法(修改密码)
 */
-(void)regist{
    [AVUser verifyMobilePhone:self.repeatPassword.text withBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [AVUser logInWithUsername:self.userNameField.text password:@"123456"]; //确保用户当前的有效登录状
            NSString *password = [self md5StrWithString:self.passwordField.text];
            [[AVUser currentUser] updatePassword:@"123456" newPassword:password block:^(id object, NSError *error) {
                if (error) {
                    //NSLog(@"密码没成功,原因%@",error);
                    [self showAlert:@"提 示" andAlertString:error.userInfo[@"error"]];
                }else{ 
                    [self showAlert:@"注册成功" andAlertString:@"" andHandler:^(UIAlertAction *action) {
                        DissMissBack;
                    }];
                }
            }];
        }else{
            [self showAlert:@"提 示" andAlertString:error.userInfo[@"error"]];
        }
    }];
}

/**
 * 重置密码方法
 */
-(void)resetPassword{
    NSString *password = [self md5StrWithString:self.passwordField.text];
    [AVUser resetPasswordWithSmsCode:self.repeatPassword.text newPassword:password block:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [self showAlert:@"密码找回成功" andAlertString:@"" andHandler:^(UIAlertAction *action) {
                DissMissBack;
            }];
        } else {
            //NSLog(@"密码找回失败,原因:%@",error.userInfo[@"error"]);
            NSString *erroInfo = error.userInfo[@"error"];
            if ([erroInfo isEqualToString:@"An user with the specified mobile phone number was not found"]) {
                erroInfo = @"此号码尚未注册";
            }
            [self showAlert:@"提 示" andAlertString:erroInfo];
        }
    }];
}

/**
 * 检查手机号码是否正确,如果是注册页面是否注册过
 */
-(void)checkPhoneNum{
    if (self.userNameField.text.length == 0 || [self.userNameField.text isEqualToString:self.userNameField.placeholder]) {
      [self showAlert:@"注 意" andAlertString:@"请输入正确的手机号码"];
    }
    if (!self.pageTypeFlag) {
        //2.再验证手机号是否被注册()
        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
        [query whereKey:@"mobilePhoneNumber" equalTo:self.userNameField.text ];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                // 检索成功
                for (AVUser *user in objects) {
                    if (user.mobilePhoneVerified && [user.mobilePhoneNumber isEqualToString:self.userNameField.text]) {
                        [self showAlert:@"提 示" andAlertString:@"此号码已经成功注册过"];
                        return ;
                    }
                }
                //NSLog(@"Successfully retrieved %ld posts.", objects.count);
            } else {
                // 输出错误信息
                //NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
        }];
    }
}

/**
 * 获取注册验证码和注册(此处是伪注册,手机并未验证)
 */
-(void)getTokenAndRegist{
    //验证手机号是否被注册过 且手机没验证()
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"mobilePhoneNumber" equalTo:self.userNameField.text ];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 检索成功
            BOOL flag = YES;
            for (AVUser *user in objects) {
                if (!user.mobilePhoneVerified) {
                    flag = NO;
                    [AVUser requestMobilePhoneVerify:self.userNameField.text withBlock:^(BOOL succeeded, NSError *error) {
                        if(succeeded){
                            return;
                        }
                    }];
                }
            }
            if (flag) {
                self.avuser.username = self.userNameField.text;
                self.avuser.mobilePhoneNumber = self.userNameField.text;
                self.avuser.password = @"123456";
                NSError *error = nil;
                [self.avuser signUp:&error];
                
                if (error) {
                    NSString *erroInfo = error.userInfo[@"error"];
                    if ([erroInfo isEqualToString:@"Mobile phone number has already been taken"]) {
                        erroInfo = @"手机号码已经被注册";
                    }
                    [self showAlert:@"提 示" andAlertString:erroInfo];
                }
                if (error) {
                    //NSLog(@"注册获取token错误,错误原因:%@",error);
                }
            }
            //NSLog(@"Successfully retrieved %ld posts.", objects.count);
        } else {
            // 输出错误信息
            //NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];
    
}

/**
 * 获取重置密码的验证码
 */
-(void)getTokenForResetPassword{
    [AVUser requestPasswordResetWithPhoneNumber:self.userNameField.text block:^(BOOL succeeded, NSError *error) {
        if (!succeeded) {
            NSString *erroInfo = error.userInfo[@"error"];
            if ([erroInfo isEqualToString:@"An user with the specified mobile phone number was not found"]) {
                erroInfo = @"此号码尚未注册";
            }
            [self showAlert:@"提 示" andAlertString:erroInfo];
        }
    }];
}

/**
 * 设置改变tokenButton的title
 */

-(void)changeGetToken:(NSTimer *)sender{
    if (self.time > 1) {
        --self.time;
        NSString *second = [NSString stringWithFormat:@"%ld s",self.time];
        self.getTokenButton.titleLabel.text = second;
        [self.getTokenButton setTitle:second forState:UIControlStateNormal];
    }else{
        self.getTokenButton.userInteractionEnabled = YES;
        self.getTokenButton.backgroundColor = [UIColor orangeColor];
        [self.getTokenButton setTitle:[NSString stringWithFormat:@"点击获取"] forState:UIControlStateNormal];
        [sender setFireDate:[NSDate distantFuture]];
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
